package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haoze.common.config.RedisUtil;
import com.haoze.common.dto.AgeDTO;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.OrdersFileIndexDataEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.MedicalDTO;
import com.haoze.nurseapp.dto.task.OrdersFileIndexDataDTO;
import com.haoze.nurseapp.enumeration.*;
import com.haoze.nurseapp.model.PuncureChannleEntity;
import com.haoze.nurseapp.service.NurseFileIndexService;
import com.haoze.nurseapp.service.NursePatientOrderService;
import com.haoze.nurseapp.service.TaskBatchService;
import com.haoze.nurseapp.service.feign.AssessmentScaleService;
import com.haoze.nurseapp.vo.*;
import com.haoze.nurseapp.vo.batch.PuncureChannleVo;
import com.haoze.nurseapp.vo.batch.TaskTransferVo;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class TaskBatchServiceImpl implements TaskBatchService {

    private static final Logger log = LoggerFactory.getLogger(TaskBatchServiceImpl.class);

    @Resource
    TaskExecuteBatchMapper taskExecuteBatchMapper;
    @Resource
    NurseFileIndexService fileIndexService;
    @Resource
    TransfusionMapper transfusionMapper;
    @Resource
    OrdersFileIndexDataMapper ordersFileIndexDataMapper;
    @Resource
    NursePatientOrderService patientOrderService;
    @Resource
    TaskExecuteMapper taskExecuteMapper;
    @Resource
    PuncureChannleMapper puncureChannleMapper;
    @Resource
    RedisUtil redisUtil;
    @Autowired
    private EmrFileMapper emrFileMapper;
    @Resource
    EmrTemplateMapper emrTemplateMapper;
    @Autowired
    AssessmentScaleService assessmentScaleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result writeFileAndCreateNextNode(String qrCode, String actionName, String otherQrCode, String punctureChannleId, String changeType) {
        String oldInpatorderdataId = null;
        String oldbatchNo = null;
        if ("changeInfusion".equals(actionName)) {
            List<PuncureChannleEntity> list = puncureChannleMapper.selectPointListById(punctureChannleId);
            if (!CollectionUtils.isEmpty(list)) {
                if (list.size() == 1) {
                    PuncureChannleEntity puncureChannleEntity = list.get(0);
                    oldInpatorderdataId = puncureChannleEntity.getInpatorderdataId();
                    oldbatchNo = puncureChannleEntity.getBatchNo();
                    puncureChannleEntity.setSpeedValue("");
                    puncureChannleEntity.setSpeedElementId("");
                    puncureChannleEntity.setChannleTypeValue("");
                    puncureChannleEntity.setChannleTypeElementId("");
                    puncureChannleEntity.setInstrumentValue("");
                    puncureChannleEntity.setInstrumentElementId("");
                    puncureChannleMapper.updateByPrimaryKeySelective(puncureChannleEntity);
                } else {
                    puncureChannleMapper.deleteByPrimaryKey(punctureChannleId);
                }
            }
        }
        long startTimeMill = System.currentTimeMillis();
        Map<String, Map<String, String>> concurrentHashMap = new ConcurrentHashMap<>();
        Map<String, List<OrdersFileIndexDataEntity>> childlist = new ConcurrentHashMap<>();
        Map<String, String> oldDataMap = new ConcurrentHashMap<>();
        Map<String, Map<String, String>> actionMap = new ConcurrentHashMap<>();
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //1.根据actionName查询task—transfer的内容
        List<TaskTransferVo> list = taskExecuteBatchMapper.selectTaskTransfer(actionName);
        if (CollectionUtils.isEmpty(list)) {
            return ResultGenerator.genFailedResult("没有任何相关配置");
        }
        //获取文书明细内容
        String finalOldInpatorderdataId = oldInpatorderdataId;
        String finalOldbatchNo = oldbatchNo;
        list.stream().forEach(x -> {
            boolean isReplace = x.getIsReplace() == 1 ? true : false;
            boolean isSave = x.getIsSave() == 1 ? true : false;
            boolean isCreateNextBatch = x.getIsCreateNextBatch() == 1 ? true : false;
            Map<String, String> taskInfo = taskExecuteBatchMapper.selectEmrFileIdByQrCode(qrCode, null);
            String saveQrcode = taskInfo.get("QR_CODE");
            //3.replaceSourceType=self判断是从上个节点替换还是指定节点替换
            if ((null != x.getReplaceSourceType() && "other".equalsIgnoreCase(x.getReplaceSourceType())) || (null != x.getSaveSourceType() && "other".equalsIgnoreCase(x.getSaveSourceType()))) {
                if (qrCode.equals(otherQrCode) && x.getIsReplace().equals(1)) {
                    return;
                }
                //4.获取指定qrcode的文书id
//                if(isSave && !isReplace) {
                taskInfo = taskExecuteBatchMapper.selectEmrFileIdByQrCode(otherQrCode, "save");
//                }else{
//                    taskInfo = taskExecuteBatchMapper.selectEmrFileIdByQrCode(otherQrCode, null);
//                }
                saveQrcode = taskInfo.get("QR_CODE");
            }
            List<OrdersFileIndexDataEntity> fileIndexDataEntitys = transfusionMapper.queryFileIndexList(taskInfo.get("EMR_FILE_ID"));
            for (int i = 0; i < fileIndexDataEntitys.size(); i++) {
                OrdersFileIndexDataEntity fileIndexDataEntity = fileIndexDataEntitys.get(i);
                //2.根据isReplace判断是否替换节点内容
                if (isReplace) {
                    if (x.getReplaceElementId().equals(fileIndexDataEntity.getElementId())) {
                        log.info("更新上级文书");
                        fileIndexDataEntity.setDataCode(x.getReplaceBasicDataCode());    //字典ID，目前给的固定值
                        fileIndexDataEntity.setDataValue(x.getReplaceBasicDataValue());   //字典值，目前给定固定值
                        ordersFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
                        if (x.getReplaceElementVarCode().equalsIgnoreCase(VarCodeEnum.SY_JSFS.getVarCode())) {
                            puncureChannleMapper.updateByQrcode(taskInfo.get("INPATORDERDATA_ID"), taskInfo.get("BATCH_NO"), qrCode);
                        } else if (x.getReplaceElementVarCode().equalsIgnoreCase(VarCodeEnum.SYLK_SYRK.getVarCode())) {
                            puncureChannleMapper.updateStatusByQrcode(taskInfo.get("INPATORDERDATA_ID"), taskInfo.get("BATCH_NO"), qrCode);
                        }
                    }
                }
                //6.根据is_save判断是否保存上个节点或者其他节点的文书内容
                //7.判断是否是替换其他节点
                if (isSave) {
                    if (x.getSaveElementId().equals(fileIndexDataEntity.getElementId())) {
                        //有些数据元是级联出来的，所以只能根据父data_Id获得子数据元
                        if (x.getSaveElementType().equalsIgnoreCase("self")) {
                            log.info("保存上级文书部分内容");
                            Map<String, String> map = new HashMap<>();
                            map.put("dataCode", fileIndexDataEntity.getDataCode());
                            map.put("dataValue", fileIndexDataEntity.getDataValue());
                            if (null != x.getActionCode()) {
                                map.put("actionCode", x.getActionCode());
                                map.put("actionValue", x.getActionValue());
                            }
                            concurrentHashMap.put(x.getSaveElementId(), map);
                        } else if (x.getSaveElementType().equalsIgnoreCase("parent")) {
                            log.info("保存其他文书部分内容");
                            //获得element_id为x.getSaveElementId()的子数据元
                            Map<String, String> map = new HashMap<>();
                            if (null != x.getActionCode()) {
                                map.put("actionCode", x.getActionCode());
                                map.put("actionValue", x.getActionValue());
                            }
                            oldDataMap.put(x.getSaveElementId(), fileIndexDataEntity.getFileIndexDataId());
                            actionMap.put(fileIndexDataEntity.getFileIndexDataId(), map);
                            List<OrdersFileIndexDataEntity> ordersFileIndexDataEntities = this.taskExecuteBatchMapper.selectChildElementByParentElementId(x.getSaveElementId(), saveQrcode);
                            //新增通道时 获取最新的文书穿刺点会有问题（新增通道未保存会使得穿刺点往后加，暂时不动原来逻辑） 优先选择选中通道信息
                            if (StringUtils.isNotBlank(punctureChannleId)) {
                                String xzccElementId = emrTemplateMapper.getSysElementIdByVarCode(VarCodeEnum.SYZX_NODE.getVarCode());
                                PuncureChannleEntity puncureChannleEntity = puncureChannleMapper.selectByPrimaryKey(punctureChannleId);
                                if (puncureChannleEntity != null) {
                                    //穿刺点
                                    ordersFileIndexDataEntities.parallelStream().filter(ordersFile -> xzccElementId.equals(ordersFile.getElementId())).forEach(ordersFile -> {
                                        Map<String, String> trueMap = emrFileMapper.findTrueFlag(xzccElementId, puncureChannleEntity.getPointValue());
                                        ordersFile.setDataCode(trueMap.get("dataCode"));
                                        ordersFile.setDataValue(trueMap.get("dataValue"));
                                    });
                                    //删除原来对应穿刺工具的输液部位数据
                                    for (int jj = 0; jj < ordersFileIndexDataEntities.size(); jj++) {
                                        OrdersFileIndexDataEntity ordersFile = ordersFileIndexDataEntities.get(jj);
                                        if (puncureChannleEntity.getToolElementId().equals(ordersFile.getElementId())) {
                                            String medicalId = ordersFile.getMedicalId();
                                            String dataRelationIds = ordersFile.getDataCode();
                                            Result result = assessmentScaleService.dynamicCascade(medicalId, dataRelationIds, null);
                                            if (result.getData() != null) {
                                                List<MedicalDTO> medicalDTOS = JSONObject.parseArray(JSONObject.toJSONString(result.getData()), MedicalDTO.class);
                                                if (!CollectionUtils.isEmpty(medicalDTOS)) {
                                                    MedicalDTO medicalDTO = medicalDTOS.get(0);
                                                    String positionElementId = medicalDTO.getElement().getId();
                                                    if (StringUtils.isNotBlank(positionElementId)) {
                                                        for (int xx = 0; xx < ordersFileIndexDataEntities.size(); xx++) {
                                                            if (positionElementId.equals(ordersFileIndexDataEntities.get(xx).getElementId())) {
                                                                ordersFileIndexDataEntities.remove(xx);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //穿刺工具
                                    for (int xx = 0; xx < ordersFileIndexDataEntities.size(); xx++) {
                                        OrdersFileIndexDataEntity ordersFile = ordersFileIndexDataEntities.get(xx);
                                        if (puncureChannleEntity.getToolElementId().equals(ordersFile.getElementId())) {
                                            Map<String, String> trueMap = emrFileMapper.findTrueFlag(puncureChannleEntity.getToolElementId(), puncureChannleEntity.getToolValue());
                                            ordersFile.setDataCode(trueMap.get("dataCode"));
                                            ordersFile.setDataValue(trueMap.get("dataValue"));
                                            String medicalId = ordersFile.getMedicalId();
                                            String dataRelationIds = ordersFile.getDataCode();
                                            if (StringUtils.isNotBlank(puncureChannleEntity.getToolPositionElementId())) {
                                                Result result = assessmentScaleService.dynamicCascade(medicalId, dataRelationIds, null);
                                                if (result.getData() != null) {
                                                    List<MedicalDTO> medicalDTOS = JSONObject.parseArray(JSONObject.toJSONString(result.getData()), MedicalDTO.class);
                                                    if (!CollectionUtils.isEmpty(medicalDTOS)) {
                                                        MedicalDTO medicalDTO = medicalDTOS.get(0);
                                                        String positionElementId = medicalDTO.getElement().getId();
                                                        String positionMedicalId = medicalDTO.getElement().getMedicalId();
                                                        OrdersFileIndexDataEntity positionOrdersFile = new OrdersFileIndexDataEntity();
                                                        positionOrdersFile.setFileIndexDataId(UUIDUtil.randomString());
                                                        positionOrdersFile.setDataVersion(ordersFile.getDataVersion());
                                                        positionOrdersFile.setCreateTime(ordersFile.getCreateTime());
                                                        positionOrdersFile.setModifyTime(ordersFile.getModifyTime());
                                                        positionOrdersFile.setHospitalId(ordersFile.getHospitalId());
                                                        positionOrdersFile.setEmrFileId(ordersFile.getEmrFileId());
                                                        positionOrdersFile.setSortId(1);
                                                        positionOrdersFile.setElementId(positionElementId);
                                                        Map<String, String> positionMap = emrFileMapper.findTrueFlag(puncureChannleEntity.getToolPositionElementId(), puncureChannleEntity.getToolPositionValue());
                                                        if (positionMap != null) {
                                                            positionOrdersFile.setDataCode(positionMap.get("dataCode"));
                                                            positionOrdersFile.setDataValue(positionMap.get("dataValue"));
                                                        }
                                                        positionOrdersFile.setParentFileIndexDataId(ordersFile.getFileIndexDataId());
                                                        positionOrdersFile.setShowIdentification("0");
                                                        positionOrdersFile.setPrintIdentification("0");
                                                        positionOrdersFile.setDeleteIdentification("0");
                                                        positionOrdersFile.setMedicalId(positionMedicalId);
                                                        ordersFileIndexDataEntities.add(positionOrdersFile);
                                                        System.out.println(ordersFileIndexDataEntities);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                            childlist.put(fileIndexDataEntity.getFileIndexDataId(), ordersFileIndexDataEntities);

                        }
                    }
                }
            }
            //5.根据is_create_next_task判断是否创建下个节点
            if (isCreateNextBatch) {
                //5-1.创建下个节点
                if ("changeInfusion".equals(actionName)) {
                    //如果当前在输液巡视上，更改文书
                    if (StringUtils.isNotBlank(finalOldInpatorderdataId) && StringUtils.isNotBlank(finalOldbatchNo)) {
                        List<Map<String, String>> maps = taskExecuteBatchMapper.queryQrCodeByInpatorderdataIdAndBatchNo(finalOldInpatorderdataId, finalOldbatchNo);
                        if (!CollectionUtils.isEmpty(maps)) {
                            String varCode = (String) maps.get(0).get("varCode");
                            if (VarCodeEnum.RWJD_SYXS.getVarCode().equals(varCode)) {
                                if ("2".equals(changeType)) {
                                    this.ordersFileIndexDataMapper.updateXSCZByInpatorderdataId(finalOldInpatorderdataId, finalOldbatchNo);
                                    this.ordersFileIndexDataMapper.updateEmrFileDataSealingTubeByInpatorderdataId(finalOldInpatorderdataId, finalOldbatchNo);
                                } else {
                                    this.ordersFileIndexDataMapper.updateSYWCByInpatorderdataId(finalOldInpatorderdataId, finalOldbatchNo);
                                    this.ordersFileIndexDataMapper.updateEmrFileDataSealingTubeByInpatorderdataId(finalOldInpatorderdataId, finalOldbatchNo);
                                }
                            }
                        }
                    }
                }
                patientOrderService.createNextTaskNode(taskInfo.get("TASK_EXECUTE_DETAIL_ID"), Integer.valueOf(taskInfo.get("BATCH_NO")), userId, taskInfo.get("GROUP_ID") == null ? "" : taskInfo.get("GROUP_ID"), "", null, saveQrcode, null);
            }
        });
        long secoundTimeMill = System.currentTimeMillis();
        String newEmrFileId = taskExecuteBatchMapper.selectNextNodeEmrFileId(qrCode);
        TaskNodeVO taskNodeVO = new TaskNodeVO();
        log.info("repalceAndSave耗时-----------------------------------------------------------------：{}毫秒", secoundTimeMill - startTimeMill);
        //6.获取下个节点的文书内容/指定节点的文书内容
        //创建下一个节点后获取最新的文书id
        //8.循环文书内容，找到对应的elementId，进行替换，获得根据action_code判断保存的文书的数据元是否有特殊操作，如不可编辑，隐藏等,修改滴速使用此分支
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            concurrentHashMap.keySet().stream().forEach(x -> {
                Map<String, String> map = concurrentHashMap.get(x);
                //根据fileIndexDataId更新dataCode和dataValue
                OrdersFileIndexDataEntity ordersFileIndexDataEntity = ordersFileIndexDataMapper.selectFileIndexDataByElementId(x, newEmrFileId);
                ordersFileIndexDataEntity.setDataCode(map.get("dataCode"));
                ordersFileIndexDataEntity.setDataValue(map.get("dataValue"));
                if (null != map.get("actionCode")) {
                    Map<String, Object> tmpMap = JSONUtils.jsonToMap(ordersFileIndexDataEntity.getElementProperty());
                    tmpMap.put(map.get("actionCode"), map.get("actionValue"));
                    ordersFileIndexDataEntity.setElementProperty(JSONUtils.beanToJson(tmpMap));
                }
                ordersFileIndexDataMapper.updateByPrimaryKeySelective(ordersFileIndexDataEntity);
            });
        }
        if (!CollectionUtils.isEmpty(childlist)) {
            oldDataMap.keySet().stream().forEach(x -> {
                List<OrdersFileIndexDataEntity> saveList = new CopyOnWriteArrayList<>();
                //如果需要保存的是父节点下的所有文书内容，就把该父节点下的文书内容删除，并且循环childlist新增文书明细
                //先删除父节点下的文书明细
                OrdersFileIndexDataEntity ordersFileIndexDataEntity = ordersFileIndexDataMapper.selectFileIndexDataByElementId(x, newEmrFileId);
                //保存子文书明细
                String oldFileIndexDataId = oldDataMap.get(x);
                List<OrdersFileIndexDataEntity> saveChildList = childlist.get(oldFileIndexDataId);
                Map<String, String> keyIdMap = new ConcurrentHashMap<>();
                //记录所有要替换的文书父id和文书对应的id
                setChildForInsert(saveChildList, ordersFileIndexDataEntity.getFileIndexDataId(), oldFileIndexDataId, keyIdMap);
                long thirdTimeMill = System.currentTimeMillis();
                log.info("递归耗时-----------------------------------------------------------------：{}", thirdTimeMill - secoundTimeMill);
                saveChildList.stream().forEach(z -> {
                    z.setParentFileIndexDataId(keyIdMap.get(z.getParentFileIndexDataId()));
                    //父子关联同时修改file_index_data_id
                    z.setFileIndexDataId(keyIdMap.get(z.getFileIndexDataId()));
                    z.initAdd();
                    Map<String, String> map = actionMap.get(oldFileIndexDataId);
                    if (null != map) {
                        Map<String, Object> tmpMap = JSONUtils.jsonToMap(z.getElementProperty());
                        if (CollectionUtils.isEmpty(tmpMap)) {
                            tmpMap = new HashMap<>();
                        }
                        tmpMap.put(map.get("actionCode"), map.get("actionValue"));
                        z.setElementProperty(JSONUtils.beanToJson(tmpMap));
                    }
                    z.setEmrFileId(ordersFileIndexDataEntity.getEmrFileId());
                    saveList.add(z);
                });
                taskExecuteBatchMapper.deleteChildEmrFileData(x, newEmrFileId);
                if (!CollectionUtils.isEmpty(saveList))
                    ordersFileIndexDataMapper.insertAllFileIndexData(saveList);
            });
        }
        long thirdTimeMill = System.currentTimeMillis();
        log.info("saveFileIndex耗时-----------------------------------------------------------------：{}", thirdTimeMill - secoundTimeMill);
        Map<String, String> taskInfo = taskExecuteBatchMapper.selectBatchInfoByQrcode(qrCode);
        //新增穿刺判断穿刺点，自动替换成未使用的穿刺点
        if (actionName.equals("insertPuncture")) {
            //根据文书id获取穿刺点
            List<OrdersFileIndexDataDTO> fileIndexDataEntitys = ordersFileIndexDataMapper.selectDataByEmrFileId(newEmrFileId);
            //查询是否存在该穿刺点
            List<OrdersFileIndexDataDTO> pointList = fileIndexDataEntitys.parallelStream().filter(x -> null != x.getVarCode() && x.getVarCode().equals(VarCodeEnum.SYZX_NODE.getVarCode())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(pointList)) {
                OrdersFileIndexDataDTO point = pointList.get(0);
                String pointStr = point.getDataValue();
                //如果存在则替换穿刺点并更新文书
                Integer pointCount = this.puncureChannleMapper.selectInfoByPointInfo(taskInfo.get("INPAT_NUM"), pointStr);
                if (pointCount > 0) {
                    //查询该患者所有未使用的穿刺点
                    Map<String, Object> unUsedPoint = this.puncureChannleMapper.selectUnUsedPointList(taskInfo.get("INPAT_NUM"));
                    if (!CollectionUtils.isEmpty(unUsedPoint)) {
                        OrdersFileIndexDataEntity fileIndexDataEntity = new OrdersFileIndexDataEntity();
                        fileIndexDataEntity.setDataValue((String) unUsedPoint.get("DATA_VALUE_REMARK"));
                        fileIndexDataEntity.setDataCode((String) unUsedPoint.get("BASICDATAVALUE_ID"));
                        fileIndexDataEntity.setFileIndexDataId(point.getFileIndexDataId());
                        this.ordersFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
                    }

                }
            }
        }

        EmrFile emrFile = fileIndexService.getFileIndex(newEmrFileId);
        taskNodeVO.setEmrFile(emrFile);
        //9.返回文书内容
        taskNodeVO.setNodeType(NodeEnterEnum.NORMAL.getValue());
        taskNodeVO.setNodeTypeName(NodeEnterEnum.NORMAL.getText());
        taskNodeVO.setQrCode(qrCode);
        //返回病人信息
        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setMedicalNum(taskInfo.get("MEDICAL_NUM"));
        patientInfo.setBedNo(taskInfo.get("BED_NO"));
        patientInfo.setBedLabel(taskInfo.get("bedLabel"));
        patientInfo.setSex(taskInfo.get("SEX"));
        //计算年龄
        patientInfo.setAge(computeAge(taskInfo));
        patientInfo.setPatName(taskInfo.get("PAT_NAME"));
        taskNodeVO.setPatientInfo(patientInfo);
        List<OrderInfo> orderInfoList = taskExecuteMapper.queryOrderInfos(taskInfo.get("INPATORDERDATA_ID"), taskInfo.get("INPAT_NUM"));
        taskNodeVO.setOrderInfoList(orderInfoList);
        taskNodeVO.setTaskNodeId(taskInfo.get("taskNodeId"));
        if (actionName.equals("insertPuncture")) {
            taskNodeVO.setNodeName("新增穿刺");
        } else if (actionName.equals("insertChannle")) {
            taskNodeVO.setNodeName("新增通道");
        } else if (actionName.equals("changeInfusion")) {
            taskNodeVO.setNodeName("更换输液");
        }

        try {
            //暂时先用这种方法处理执行时间，后续如果其他类型也需要这样显示 需要另外想方法
            String[] qrCodes = qrCode.split("_");
            String executeTimeStr = qrCodes[1].substring(qrCodes[1].length() - 14);
            Date executeTime = DateUtil.stringToDate(executeTimeStr, "yyyyMMddHHmmss");
            String execTimeStr = DateUtil.dateToString(executeTime, "yyyy-MM-dd HH:mm:ss");
            taskNodeVO.setExecTime(execTimeStr);
        } catch (Exception e) {
            taskNodeVO.setExecTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        String orderInfoFreq = taskExecuteMapper.queryOrderInfoFreq(taskInfo.get("INPATORDERDATA_ID"));
        orderInfoList.get(0).setFreq((StringUtils.isBlank(orderInfoList.get(0).getFreq()) ? "" : orderInfoList.get(0).getFreq()) + " " + (StringUtils.isBlank(orderInfoFreq) ? "" : orderInfoFreq));
        String taskName = taskExecuteMapper.getTaskNameByQrCode(qrCode);
        if (ConstsEnum.TASK_NAME_JMZS.getName().equals(taskName)) {
            taskNodeVO.setSpecialNodeType(SpecialNodeEnum.JMZS.getValue());
            taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.JMZS.getText());
        }
        //获取所有在患者身上的穿刺点
        if (MapUtils.isNotEmpty(taskInfo)) {
            if (taskInfo.get("cancelDatetime") != null) {
                return ResultGenerator.genFailedResult("该医嘱已取消");
            }
            // 只有长期医嘱才需要判断结束时间
            if ("长期医嘱".equals(taskInfo.get("orderClassName")) && OrderStatusEnum.ORDER_STOP_HIS.getValue().equals(taskInfo.get("execStatusHis")) && taskInfo.get("planEndDatetime") != null && taskInfo.get("planEndDatetime").compareTo(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")) < 0) {
                return ResultGenerator.genFailedResult("该医嘱已停止");
            }

//			if (map.get("confirmDatetime") == null || (!map.get("confirmDatetime").equals(map.get("createDatetime")) && !map.get("confirmDatetime").equals(DateUtil.dateToString(DateUtil.getDateBefore(new Date(), 1), "yyyy-MM-dd")))) {
//				return ResultGenerator.genFailedResult("医嘱尚未确认，无法执行");
//			}
            String execStatus = taskInfo.get("execStatus");
            if (org.apache.commons.lang.StringUtils.isNotBlank(execStatus)) {
                if (StateEnum.ORDER_INVALID.getValue().equals(execStatus)) {
                    return ResultGenerator.genFailedResult("该医嘱已" + StateEnum.ORDER_INVALID.getText());
                }
                if (StateEnum.ORDER_DEL.getValue().equals(execStatus)) {
                    return ResultGenerator.genFailedResult("该医嘱已" + StateEnum.ORDER_DEL.getText());
                }
                if (StateEnum.ORDER_CANCEL.getValue().equals(execStatus)) {
                    return ResultGenerator.genFailedResult("该医嘱已" + StateEnum.ORDER_CANCEL.getText());
                }
            }
        }
        return ResultGenerator.genOkResult(taskNodeVO);
    }

    void setChildForInsert(List<OrdersFileIndexDataEntity> saveChildList, String newFileDataId, String oldFileIndexDataId, Map<String, String> keyIdMap) {
        saveChildList.stream().filter(y -> y.getParentFileIndexDataId().equals(oldFileIndexDataId)).forEach(z -> {
            log.info("保存文书ID的关系");
            keyIdMap.put(z.getParentFileIndexDataId(), newFileDataId);
            String fileIndexDataId = UUIDUtil.randomString();
            //父子关联同时修改file_index_data_id
            keyIdMap.put(z.getFileIndexDataId(), fileIndexDataId);
            setChildForInsert(saveChildList.stream().filter(x -> null == keyIdMap.get(x.getFileIndexDataId()) && !x.getParentFileIndexDataId().equals(oldFileIndexDataId)).collect(Collectors.toList())
                    , fileIndexDataId, z.getFileIndexDataId(), keyIdMap);
        });
    }

    /**
     * 计算年龄
     *
     * @param patientInfo
     * @return 年龄
     */
    private String computeAge(Map<String, String> patientInfo) {
        AgeDTO ageDTO = new AgeDTO();
        ageDTO.setAgeYear(patientInfo.get("AGE_YEAR"));
        ageDTO.setAgeMonth(patientInfo.get("AGE_MONTH"));
        ageDTO.setAgeDay(patientInfo.get("AGE_DAY"));
        ageDTO.setAgeHour(patientInfo.get("AGE_HOUR"));
        ageDTO.setAgeMinute(patientInfo.get("AGE_MINUTE"));
        ageDTO.setInDateTime(patientInfo.get("IN_DATETIME"));
        ageDTO.setBirthday(patientInfo.get("BIRTHDAY"));
        return DateUtil.getAge(ageDTO);
    }

    private void changeDataCodeValue(List<EmrFileData> emrFileDataList, String x, Map<String, Map<String, String>> concurrentHashMap, Map<String, List<OrdersFileIndexDataEntity>> childlist) {
        if (!CollectionUtils.isEmpty(concurrentHashMap)) {
            for (int i = 0; i < emrFileDataList.size(); i++) {
                EmrFileData emrFileData = emrFileDataList.get(i);
                if (x.equals(emrFileData.getFileIndexDataEntity().getElementId())) {
                    Map<String, String> map = concurrentHashMap.get(x);
                    emrFileData.getFileIndexDataEntity().setDataCode(map.get("dataCode"));    //字典ID，目前给的固定值
                    emrFileData.getFileIndexDataEntity().setDataValue(map.get("dataValue"));   //字典值，目前给定固定值
                    if (null != map.get("actionCode")) {
                        Map<String, Object> propertyMap = JSONUtils.jsonToMap(emrFileData.getFileIndexDataEntity().getElementProperty());
                        propertyMap.put(map.get("actionCode"), map.get("actionValue"));
                        emrFileData.getFileIndexDataEntity().setElementProperty(JSONUtils.beanToJson(propertyMap));
                    }
                }
                List<EmrFileData> list = emrFileDataList.get(i).getEmrFileDataList();
                if (!CollectionUtils.isEmpty(list)) {
                    changeDataCodeValue(list, x, concurrentHashMap, childlist);
                }
            }
        }
    }

    @Override
    public Result queryInfusionCenterList(String inpatNum) {
        List<PuncureChannleVo> puncureChannleEntities = puncureChannleMapper.selectInfoByIpatNum(inpatNum);
        return ResultGenerator.genOkResult(puncureChannleEntities);
    }
}